<template>
  <a-config-provider :locale="zhCN">
    <div class="page-container">
      <!-- 添加加载状态 -->
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
      </div>

      <!-- 修改顶部导航栏 -->
      <header class="header">
        <div class="logo">
          <div class="logo-wrapper">
            <img src="https://tse1-mm.cn.bing.net/th/id/OIP-C.PZ20K1hYgjV35Y8mKdeNfwHaHa?rs=1&pid=ImgDetMain" alt="logo" class="logo-img" />
            <span class="logo-text">联东大模型</span>
          </div>
          <div class="version-tag">V1.0</div>
        </div>
        <div class="header-right">
          <a-range-picker v-model:value="value1" :config="datePickerConfig" />
          <div class="header-stats">
            <div class="stat-item">
              <i class="iconfont icon-user"></i>
              <span>在线用户: 125</span>
            </div>
            <div class="stat-item">
              <i class="iconfont icon-time"></i>
              <span>{{ currentTime }}</span>
            </div>
          </div>
          <div class="select-wrapper">
            <div class="custom-select" @click="toggleDropdown">
              <span class="selected-text">{{ getSelectedText }}</span>
              <span class="select-arrow" :class="{ 'active': isDropdownOpen }">▼</span>
            </div>
            <div class="select-dropdown" v-if="isDropdownOpen">
              <div class="select-option" 
                   v-for="option in selectOptions" 
                   :key="option.value"
                   :class="{ 'active': currentType === option.value }"
                   @click="selectOption(option.value)">
                {{ option.label }}
              </div>
            </div>
          </div>
        </div>
      </header>

      <!-- 添加数据概览卡片 -->
      <!-- <div class="data-overview">
        <div class="overview-card" v-for="(stat, index) in statistics" :key="index">
          <div class="card-title">{{ stat.title }}</div>
          <div class="card-value">{{ stat.value }}</div>
          <div class="card-trend" :class="stat.trend">
            <span class="trend-icon">{{ stat.trend === 'up' ? '↑' : '↓' }}</span>
            {{ stat.percentage }}%
          </div>
        </div>
      </div> -->

      <!-- 主要内容区域 -->
      <div class="main-content">
        <!-- 总览模式 -->
        <div v-if="currentType === 'overview'" class="overview-container">
          <div class="grid-container">
            <div v-for="(item, index) in overviewItems" :key="index" 
                 class="grid-item" :class="{'highlight': item.highlight}">
              <div class="box-title">
                <a-tooltip>
                  <template #title>{{ item.tooltip }}</template>
                  <span class="title-text">{{ item.title }}</span>
                </a-tooltip>
                <!-- <div class="box-actions">
                  <span class="action-icon">⚡</span>
                  <span class="action-icon">⟳</span>
                </div> -->
              </div>
              <component :is="item.component" :title="item.title" :option="item.option"></component>
            </div>
          </div>
        </div>

        <!-- 其他模式 -->
        <div v-else class="grid-container">
          <div v-for="(item, index) in detailItems" :key="index" class="grid-item">
            <div class="box-title">
              <a-tooltip>
                <template #title>{{ item.tooltip }}</template>
                {{ item.title }}
              </a-tooltip>
            </div>
            <component :is="item.component" :title="item.title" :option="item.option"></component>
          </div>
        </div>
      </div>
    </div>
  </a-config-provider>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import type { ChartItem, StatisticItem, SelectOption, ChartOption } from './types';
import UserPie from "./components/UserPie.vue";
import { api } from './api';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
// 导入 Ant Design Vue 的中文语言包
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import { ConfigProvider } from 'ant-design-vue';

// 设置 dayjs 的语言
dayjs.locale('zh-cn');

// 设置 Ant Design Vue 的语言
ConfigProvider.config({
  locale: zhCN,
});

// 先定义所有的响应式数据
const currentType = ref('overview');
const value1 = ref<[string, string] | null>(null);
const loading = ref(false);
const isDropdownOpen = ref(false);
const currentTime = ref('');
let timer: number;

// 定义数据相关的 ref
const overviewItems = ref<ChartItem[]>([]);
const detailItems = ref<ChartItem[]>([]);
const statistics = ref<StatisticItem[]>([
  { title: '总线索数', value: '17,092,715', trend: 'up', percentage: '15' },
  { title: '今日新增', value: '2,456', trend: 'up', percentage: '5.2' },
  { title: '转化率', value: '24.5%', trend: 'down', percentage: '2.1' },
  { title: '活跃用户', value: '3,456', trend: 'up', percentage: '12.5' },
]);

// 定义配置对象
const datePickerConfig = {
  placeholder: ['开始日期', '结束日期'],
  format: 'YYYY-MM-DD',
  allowClear: true,
  dropdownClassName: 'custom-date-dropdown',
  inputReadOnly: true,
  locale: zhCN,
  showTime: false,
  style: {
    backgroundColor: 'transparent',
    borderColor: 'rgba(71, 85, 105, 0.5)',
    color: '#fff'
  }
};

const selectOptions = [
  { value: 'overview', label: '总览', enum: "0" },
  { value: 'supply-chain', label: '大模型-供应链', enum: "1" },
  { value: 'industry-cluster', label: '大模型-产业集群', enum: "2" },
  { value: 'robot', label: '大模型-机器人', enum: "3" },
  { value: 'public', label: '大模型-公海', enum: "4" }
];

// 先定义 fetchData 函数
const fetchData = async () => {
  try {
    loading.value = true;
    
    const currentEnum = selectOptions.find(option => option.value === currentType.value)?.enum || "0";
    
    const params: any = {
      task_name: currentEnum
    };
    
    if (value1.value) {
      params.start_time = dayjs(value1.value[0]).format('YYYY-MM-DD 00:00:00');
      params.end_time = dayjs(value1.value[1]).format('YYYY-MM-DD 23:59:59');
    }

    const response = await api.getStatistics(params);
    
    if (response.data?.code === 0 && response.data?.data?.items) {
      const items = response.data.data.items;
      
      const updatedCharts = items.map(item => {
        // 确保 value 是字符串类型
        const valueStr = String(item.value);
        const isPercentage = valueStr.includes('%');
        const numValue = isPercentage 
          ? parseFloat(valueStr.replace('%', '')) 
          : Number(valueStr);

        // 修改饼图配置
        return {
          title: item.name,
          tooltip: item.name,
          component: UserPie,
          option: {
            tooltip: { 
              trigger: 'item',
              formatter: (params: any) => {
                const value = isPercentage ? `${params.value}%` : params.value;
                return `${params.name}: ${value}`;
              }
            },
            legend: { 
              show: false
            },
            series: [{
              type: 'pie',
              radius: ['65%', '80%'],
              center: ['50%', '50%'],
              data: [
                { 
                  value: numValue,
                  name: item.name,
                  itemStyle: {
                    color: '#4B79E5'
                  }
                },
                {
                  value: isPercentage ? (100 - numValue) : numValue,
                  name: 'background',
                  itemStyle: {
                    color: 'rgba(255, 255, 255, 0.1)'
                  },
                  label: {
                    show: false
                  }
                }
              ],
              label: {
                show: true,
                position: 'center',
                formatter: () => {
                  return [
                    `{title|${item.name}}`,
                    `{value|${valueStr}}`
                  ].join('\n');
                },
                rich: {
                  title: {
                    color: '#fff',
                    fontSize: 14,
                    padding: [0, 0, 10, 0]
                  },
                  value: {
                    color: '#4B79E5',
                    fontSize: 24,
                    fontWeight: 'bold'
                  }
                }
              },
              emphasis: {
                disabled: true
              }
            }]
          }
        };
      });

      // 更新数据
      if (currentType.value === 'overview') {
        overviewItems.value = [...updatedCharts.slice(0, 4)];
      } else {
        const overviewTitles = overviewItems.value.map(item => item.title);

        // 根据 overviewTitles 对 detailItems 进行排序
        detailItems.value = updatedCharts.filter(chart => !chart.title.includes('CPD')).sort((a, b) => {
          const indexA = overviewTitles.indexOf(a.title);
          const indexB = overviewTitles.indexOf(b.title);
          
          // 如果在 overviewTitles 中不存在，则设置为 Infinity
          const sortedIndexA = indexA === -1 ? Infinity : indexA;
          const sortedIndexB = indexB === -1 ? Infinity : indexB;

          return sortedIndexA - sortedIndexB;
        });
      }
    }
  } catch (error) {
    console.error('数据加载失败:', error);
    // 可以添加错误提示
    // message.error('数据加载失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 然后定义其他方法
const updateTime = () => {
  const now = new Date();
  currentTime.value = now.toLocaleTimeString('zh-CN', { 
    hour12: false,
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

const getSelectedText = computed(() => {
  return selectOptions.find(option => option.value === currentType.value)?.label || '总览';
});

const toggleDropdown = () => {
  isDropdownOpen.value = !isDropdownOpen.value;
};

const selectOption = (value: string) => {
  currentType.value = value;
  isDropdownOpen.value = false;
  fetchData();
};

// 最后添加生命周期钩子和监听器
onMounted(() => {
  updateTime();
  timer = setInterval(updateTime, 1000);
  
  document.addEventListener('click', (e) => {
    const target = e.target as HTMLElement;
    if (!target.closest('.select-wrapper')) {
      isDropdownOpen.value = false;
    }
  });

  // 初始加载数据
  fetchData();
  
  // 设置定时刷新
  const refreshInterval = setInterval(fetchData, 5 * 60 * 1000);
  
  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(refreshInterval);
    clearInterval(timer);
  });
});

// 添加 watch
watch([value1, currentType], () => {
  fetchData();
}, { immediate: true, deep: true });
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #1a2a3a 0%, #0d1420 100%);
  padding: 0;
}

.header {
  position: relative;
  z-index: 1000;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 24px;
  background: rgba(13, 20, 32, 0.8);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.logo {
  display: flex;
  align-items: center;
  gap: 12px;
}

.logo-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-img {
  width: 32px;
  height: 32px;
}

.logo-text {
  color: #fff;
  font-size: 20px;
  font-weight: 600;
  background: linear-gradient(120deg, #3699FF, #8B5CF6);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.version-tag {
  padding: 2px 8px;
  background: rgba(54, 153, 255, 0.1);
  border: 1px solid rgba(54, 153, 255, 0.2);
  border-radius: 4px;
  color: #3699FF;
  font-size: 12px;
  font-weight: 500;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 24px;
}

.header-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 14px;
}

.stat-item i {
  font-size: 16px;
  color: #3699FF;
}

.select-wrapper {
  position: relative;
  width: 200px;
  z-index: 1000;
}

.custom-select {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 16px;
  background: rgba(30, 41, 59, 0.8);
  border: 1px solid rgba(71, 85, 105, 0.5);
  border-radius: 8px;
  cursor: pointer;
  color: #fff;
  transition: all 0.3s ease;
}

.custom-select:hover {
  background: rgba(30, 41, 59, 0.9);
  border-color: rgba(71, 85, 105, 0.8);
}

.selected-text {
  font-size: 14px;
  font-weight: 500;
}

.select-arrow {
  font-size: 12px;
  transition: transform 0.3s ease;
  color: #64748b;
}

.select-arrow.active {
  transform: rotate(180deg);
}

.select-dropdown {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  width: 100%;
  background: rgba(30, 41, 59, 0.95);
  border: 1px solid rgba(71, 85, 105, 0.5);
  border-radius: 8px;
  overflow: hidden;
  animation: dropdownFadeIn 0.2s ease;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
  z-index: 1000;
}

.select-option {
  padding: 10px 16px;
  color: #cbd5e1;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.select-option:hover {
  background: rgba(71, 85, 105, 0.3);
  color: #fff;
}

.select-option.active {
  background: rgba(59, 130, 246, 0.2);
  color: #3b82f6;
}

@keyframes dropdownFadeIn {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 更新响应式样式 */
@media screen and (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 12px;
    padding: 12px;
  }
  
  .header-right {
    width: 100%;
    flex-direction: column;
    gap: 12px;
  }
  
  .header-stats {
    width: 100%;
    justify-content: space-between;
  }
  
  .select-wrapper {
    width: 100%;
  }
}

.data-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  padding: 20px;
  position: relative;
  z-index: 1;
}

.overview-card {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 12px;
  padding: 16px;
  color: #fff;
  transition: transform 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-5px);
}

.card-title {
  font-size: 14px;
  opacity: 0.8;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin: 8px 0;
}

.card-trend {
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.card-trend.up { color: #67C23A; }
.card-trend.down { color: #F56C6C; }

.main-content {
  position: relative;
  z-index: 1;
  padding: 20px;
}

.grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.grid-item {
  background: rgba(30, 41, 59, 0.5);
  border-radius: 12px;
  padding: 16px;
  height: 350px;  /* 设置固定高度 */
  display: flex;
  flex-direction: column;
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  animation: fadeIn 0.5s ease-out;
}

.grid-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.3);
}

.box-title {
  flex-shrink: 0;  /* 防止标题被压缩 */
  margin-bottom: 16px;
}

/* 图表容器样式 */
.grid-item > :deep(div) {
  flex: 1;  /* 让图表容器占满剩余空间 */
  min-height: 0;  /* 重要：允许内容缩小 */
}

.title-text {
  display: flex;
  align-items: center;
}

.box-actions {
  display: flex;
  gap: 8px;
}

.action-icon {
  cursor: pointer;
  opacity: 0.6;
  transition: opacity 0.3s;
}

.action-icon:hover {
  opacity: 1;
}

.highlight {
  border: 2px solid #409EFF;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.overview-container .grid-container {
  grid-template-columns: repeat(4, 1fr);
}

/* 添加加载样式 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 日期选择器的全局样式 */
:deep(.ant-picker) {
  background-color: rgba(30, 41, 59, 0.8) !important;
  border-color: rgba(71, 85, 105, 0.5) !important;
}

:deep(.ant-picker-input > input) {
  color: #fff !important;  /* 输入框文字颜色 */
  background-color: transparent !important;  /* 输入框背景透明 */
}

:deep(.ant-picker-input > input::placeholder) {
  color: rgba(255, 255, 255, 0.6) !important;  /* 占位符文字颜色 */
}

:deep(.ant-picker-separator),
:deep(.ant-picker-suffix) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.ant-picker-clear) {
  background: rgba(30, 41, 59, 0.8) !important;
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.custom-date-dropdown) {
  background: rgba(30, 41, 59, 0.95) !important;
  border-color: rgba(71, 85, 105, 0.5) !important;
}

:deep(.custom-date-dropdown .ant-picker-cell) {
  color: rgba(255, 255, 255, 0.8) !important;
}

:deep(.custom-date-dropdown .ant-picker-cell-in-view) {
  color: #fff !important;
}

:deep(.custom-date-dropdown .ant-picker-header) {
  color: #fff !important;
  border-bottom-color: rgba(255, 255, 255, 0.1) !important;
}

:deep(.custom-date-dropdown .ant-picker-header button) {
  color: rgba(255, 255, 255, 0.6) !important;
}

:deep(.custom-date-dropdown .ant-picker-cell:hover) {
  background: rgba(54, 153, 255, 0.1) !important;
}

:deep(.custom-date-dropdown .ant-picker-cell-selected .ant-picker-cell-inner) {
  background: #3699FF !important;
}

/* 添加占位符文字的样式 */
:deep(.ant-picker-placeholder) {
  color: rgba(255, 255, 255, 0.6) !important;
}
</style>